import APlayer from 'aplayer'
import { addLyricToMusic } from '@/utils/common'
import { getUserMusic } from '@/network/blog/music.request'
import eventBus from '@/utils/eventBus'

const openMusic = () => {
  const localUser = JSON.parse(localStorage.getItem('user')) || {}
  let indexOfUserId = window.location.pathname.split('/').indexOf('u') + 1
  let userId = Number(window.location.pathname.split('/')[indexOfUserId])
  userId = isNaN(userId) ? localUser.id : userId

  let ap = null

  if (userId && !ap) {
    getUserMusic(userId)
      .then((loveMusics) => {
        ap = new APlayer({
          container: document.getElementById('aplayer'),
          fixed: true,
          autoplay: false,
          theme: '#008c8c',
          lrcType: 1,
          audio: addLyricToMusic(loveMusics)
        })
      })
      .catch(console.log)
  }

  if (userId) {
    ap = null
  }

  eventBus.addListener('entry', (userId) => {
    if (!ap) {
      getUserMusic(userId)
        .then((loveMusics) => {
          ap = new APlayer({
            container: document.getElementById('aplayer'),
            fixed: true,
            autoplay: false,
            theme: '#008c8c',
            lrcType: 1,
            audio: addLyricToMusic(loveMusics)
          })
        })
        .catch(console.log)
    }
  })

  eventBus.addListener('exit', () => {
    ap.pause()
    ap.list.hide('--show-hidden')
    ap && ap.list.clear()
    ap && ap.destroy()
    ap = null
  })
}

export default openMusic
